from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from api import models
from rest_framework.response import Response
from api.serializer.auction import AuctionModelSerializer, AuctionItemModelSerializer, \
    AuctionItemDetailViewModelSerializer, AuctionDepositViewModelSerializer, AuctionItemImgaeModelSerializer, \
    TopicViewModelSerializer
from api.pagination.pages import MinBaseFilterBackend, MaxBaseFilterBackend, AuctionPagination
from api.authentication.auth import UserAuthentication
import json


class AuctionView(ListAPIView):
    queryset = models.Auction.objects.order_by('-id')
    serializer_class = AuctionModelSerializer
    pagination_class = AuctionPagination
    filter_backends = [MinBaseFilterBackend, MaxBaseFilterBackend]


class AuctionDetailView(RetrieveAPIView):
    queryset = models.Auction.objects
    serializer_class = AuctionItemModelSerializer
    authentication_classes = [UserAuthentication]


class AuctionItemDetailView(RetrieveAPIView):
    queryset = models.AuctionItem.objects.filter(status__gt=1)
    serializer_class = AuctionItemDetailViewModelSerializer


class AuctionDepositView(RetrieveAPIView, CreateAPIView):
    authentication_classes = [UserAuthentication]
    queryset = models.AuctionItem.objects.filter(status__in=[2, 3])
    serializer_class = AuctionDepositViewModelSerializer


class AuctionItemImgae(ListAPIView):
    serializer_class = AuctionItemImgaeModelSerializer

    def post(self, request, *args, **kwargs):
        auction_item = json.loads(request.body.decode('utf8'))
        iid = auction_item.pop('id')
        if not iid:
            iid = None
        print(iid, auction_item)
        auction_obj = models.AuctionItemImage.objects.update_or_create(defaults={**auction_item}, id=iid)
        return Response({'status': True, "message": auction_obj[0].id})

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        queryset = models.AuctionItemImage.objects.filter(item_id=pk)
        return queryset

    def get(self, request, *arg, **kwargs):
        response = super().get(request, *arg, **kwargs)
        queryset = models.AuctionItemDetail.objects.filter(item_id=self.kwargs.get('pk')).first()
        if not queryset:
            return response
        context = {
            "auction_detail": response.data,
            "result": {
                "id": queryset.id,
                "key": queryset.key,
                "value": queryset.value
            }
        }
        return Response(context)


class TopicView(ListAPIView):
    queryset = models.Topic.objects
    serializer_class = TopicViewModelSerializer
